﻿using System;
using System.Threading;

namespace Microsoft.Biztalk.Adapters.Wcf.NullBinding
{
    class NullAsyncResult : IAsyncResult
    {
        public NullAsyncResult(AsyncCallback callback, object state)
        {
            this.AsyncWaitHandle = new ManualResetEvent(true);
            this.AsyncState = state;
            this.callback = callback;
            SetComplete();
        }

        public NullAsyncResult(TimeSpan timeout, AsyncCallback callback, object state)         
        {
            this.AsyncWaitHandle = new ManualResetEvent(false);
            this.AsyncState = state;
            this.callback = callback;

            if (timeout == TimeSpan.MinValue)
            {
                SetComplete();
                return;
            }

            if(timeout.TotalSeconds > Int32.MaxValue)
                timeout = new TimeSpan(0,0,Int32.MaxValue);
            timer = new Timer(new TimerCallback(SetComplete), null, (long)timeout.TotalMilliseconds, -1);
        }

        private Timer timer;
        private bool isComplete = false;
        private AsyncCallback callback;
        public object AsyncState { get; set; }
        public WaitHandle AsyncWaitHandle { get; set; }
        public bool CompletedSynchronously
        {
            get { return false; }
        }

        public bool IsCompleted
        {
            get { return this.isComplete; }
        }

        private void SetComplete(object obj)
        {
            SetComplete();
        }

        internal void SetComplete()
        {
            this.isComplete = true;
            (this.AsyncWaitHandle as ManualResetEvent).Set();

            if (this.callback != null)
            {
                this.callback(this);
            }
        }
    }
}
